let _Vue = null
export default class VueRouter {
  static install (Vue) {
    // 1. 判断当前插件是否已经被安装，如果已经被安装，则不需要重复安装
    if (VueRouter.install.installed) {
      return
    }
    VueRouter.install.installed = true
    // 2. 将Vue构造函数存储在全局变量之中
    _Vue = Vue
    // 3. 将创建VUE实例时传入的router对象注入到所有的Vue实例中
    // 混入
    _Vue.mixin({
      beforeCreate () {
        // 并不是所有的组件均混入，只混入Vue实例，即有router
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          this.$options.router.init()
        }
      }
    })
  }

  // 初始化属性
  constructor (options) {
    this.options = options
    this.routeMap = {}
    this.data = _Vue.observable({
      current: '/'
    })
  }

  createRouteMap () {
    // 遍历所有的路由规则，并将其转化为键值对，存储到routeMap
    const routes = this.options.routes || []
    routes.forEach(route => {
      this.routeMap[route.path] = route.component
    })
  }

  initComponents (Vue) {
    const _self = this
    Vue.component('router-link', {
      props: {
        to: String
      },
      // template: '<a :href="to"><slot></slot></a>' // 编译器版本
      // 运行时版本
      render (h) {
        const mode = _self.options.mode
        if (mode === 'history') {
          return h('a', {
            attrs: {
              href: this.to
            },
            on: {
              click: this.clickHandler
            }
          }, [this.$slots.default])
        } else {
          return h('a', {
            attrs: {
              href: `#${this.to}`
            },
            on: {
              click: this.clickHandler
            }
          }, [this.$slots.default])
        }
      },
      methods: {
        clickHandler (e) {
          const mode = _self.options.mode
          if (mode === 'history') {
            history.pushState({}, '', this.to)
            this.$router.data.current = this.to
            e.preventDefault()
          } else {
            window.location.hash = this.to
            // this.$router.data.current = this.to
            e.preventDefault()
          }
        }
      }
    })

    Vue.component('router-view', {
      render (h) {
        const component = _self.routeMap[_self.data.current]
        return h(component)
      }
    })
  }

  init () {
    this.createRouteMap()
    this.initComponents(_Vue)
    this.initEvent()
  }

  initEvent () {
    const mode = this.options.mode
    if (mode === 'history') {
      window.addEventListener('popstate', () => {
        this.data.current = window.location.pathname
      })
    } else {
      window.onhashchange = () => {
        this.data.current = window.location.hash.replace('#', '')
      }
    }
  }
}
